package com.tw;
import java.util.ArrayList;
import java.util.List;
import twitter4j.Status;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.auth.AccessToken;
import twitter4j.auth.RequestToken;

public class MainTweetC {
	 public static Twitter twitter = new TwitterFactory().getInstance();
	    public static AccessToken aTkn;

	    public static boolean analize(String cmd) {
	        try {
	            if (cmd.equalsIgnoreCase("")) {
	                return false;
	            }
	            if (cmd.matches("ls{1}")||cmd.matches("dir{1}")) {
	                readTweets();
	            } else if(cmd.matches("(rt-){1}[0-9]+")){
	                retweet(Long.parseLong(cmd.split("-")[1]));
	            }
	            else {
	                update(cmd);
	            }
	        } catch (Exception ex) {
	            System.out.println("Error:\n" + ex);
	        }
	        return true;
	    }

	    public static void main(String[] args) throws TwitterException {
	        twitter.setOAuthConsumer("jtjDcIRHXwtJtG0Vs9JAyg", "WEwmiYIsnErWsslxXz5zERKs1ZxV4gfWK24RYtDOc");
	        auth();
//	        aTkn = new AccessToken(/*token*/"",/*tokensecret*/ "");
	        twitter.setOAuthAccessToken(aTkn);
	        twitter.verifyCredentials();
	        String cmd;
	        do {
	            System.out.print("Tw: ");
	            cmd = System.console().readLine();
	        } while (analize(cmd.trim()));
	        System.exit(0);
	    }

	    public static void update(String update) throws TwitterException {
	        twitter.updateStatus(update);
	    }
	    public static void retweet(long id) throws TwitterException {
	        twitter.retweetStatus(id);
	    }

	    public static void readTweets() throws TwitterException {
	        List<Status> statuses = new ArrayList();
	        statuses = twitter.getFriendsTimeline();
	        System.out.println("Tweets: ");
	        Status status = null;
	        for (int i = statuses.size() - 1; i >= 0; i--) {
	            status = statuses.get(i);
	            System.out.println(status.getId() + " : " + status.getUser().getName() + ":\n" + status.getText());
	        }
	    }

	    public static void auth() throws TwitterException{
	        RequestToken requestToken = twitter.getOAuthRequestToken();
	        System.out.println("Url: \n" + requestToken.getAuthorizationURL() + "\n\n");
	        String pin;
	        while (aTkn == null) {
	            System.out.print("Pin: ");
	            pin = System.console().readLine();
	            try {
	                aTkn = twitter.getOAuthAccessToken(requestToken, pin);
	            } catch (TwitterException ex) {
	                System.out.println("Invalid");
	            }

	        }
	        System.out.println("Token: " + aTkn.getToken());
	        System.out.println("Token secret: " + aTkn.getTokenSecret());
	    }

}
